<?php

namespace Fluency;

/*
 * @package Fluency
 * @author  Ignas Rudaitis
 * @version 2.0.0
 */
class Injector
{
    private $readers = array();

    public static function create()
    {
        return new self;
    }

    public function withContainer($reader)
    {
        $clone = clone $this;
        $clone->readers[] = $reader;
        return $clone;
    }

    public function withArrayContainer($array)
    {
        $reader = function($key) use ($array) {
            return isset($array[$key]) ? $array[$key] : null;
        };
        return $this->withContainer($reader);
    }

    public function call($function, $argumentMapping)
    {
        $args = array_map(array($this, "getService"), $argumentMapping);
        return call_user_func_array($function, $args);
    }

    public function getService($keys)
    {
        foreach ((array) $keys as $key) {
            foreach ($this->readers as $reader) {
                $result = call_user_func($reader, $key);
                if ($result !== null) {
                    return $result;
                }
            }
        }
    }
}